// 全局变量
let currentDate = new Date().toISOString().split('T')[0];
const apiBaseUrl = 'http://localhost:8080/api';

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 设置默认日期为当天
    document.getElementById('date-input').value = currentDate;
    
    // 绑定查询按钮事件
    document.getElementById('query-btn').addEventListener('click', fetchAllData);
    
    // 初始加载数据
    fetchAllData();
});

// 获取所有数据
async function fetchAllData() {
    currentDate = document.getElementById('date-input').value;
    if (!currentDate) {
        alert('请选择日期');
        return;
    }
    currentDate = currentDate.replaceAll("-","")
    console.log("currentDate:",currentDate)
    
    
    try {
        // 并行获取所有数据
        const [zdfenbu, zdtcount, fbfailed, ztpool, yesZtpool, gnTop10] = await Promise.all([
            fetchData('zdfenbu'),
            fetchData('zdtcount'), 
            fetchData('fbfailed'),
            fetchData('ztpool'),
            fetchData('yes_ztpool'),
            fetchData('gn_top10')
        ]);
        
        // 渲染所有图表和表格
        renderZdfenbuChart(zdfenbu);
        renderZdtcountChart(zdtcount);
        renderFbfailedChart(fbfailed);
        renderZtpoolTable(ztpool);
        renderYesZtpoolTable(yesZtpool);
        renderGnTop10Table(gnTop10);
        
    } catch (error) {
        console.error('数据获取失败:', error);
        alert('数据获取失败，请检查网络连接或服务器状态');
    }
}

// 通用数据获取函数
async function fetchData(endpoint) {
    const response = await fetch(`${apiBaseUrl}/${endpoint}?date=${currentDate}`);
    if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
    }
    return await response.json();
}

// 渲染涨跌分布柱形图
function renderZdfenbuChart(data) {
    const container = d3.select('#zdfenbu-chart');
    container.html('');
    
    const margin = {top: 20, right: 20, bottom: 40, left: 40};
    const width = container.node().clientWidth - margin.left - margin.right;
    const height = 300 - margin.top - margin.bottom;
    
    const svg = container.append('svg')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('g')
        .attr('transform', `translate(${margin.left},${margin.top})`);
    
    // 设置比例尺
    const x = d3.scaleBand()
        .domain(data.map(d => d.range))
        .range([0, width])
        .padding(0.2);
        
    const y = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.count)])
        .nice()
        .range([height, 0]);
    
    // 添加柱形
    svg.selectAll('.bar')
        .data(data)
        .join('rect')
        .attr('class', 'bar')
        .attr('x', d => x(d.range))
        .attr('y', d => y(d.count))
        .attr('width', x.bandwidth())
        .attr('height', d => height - y(d.count))
        .attr('fill', d => d.range >= 0 ? '#e74c3c' : '#2ecc71');
    
    // 添加X轴
    svg.append('g')
        .attr('transform', `translate(0,${height})`)
        .call(d3.axisBottom(x))
        .selectAll('text')
        .attr('transform', 'rotate(-45)')
        .style('text-anchor', 'end');
    
    // 添加Y轴
    svg.append('g')
        .call(d3.axisLeft(y));
    
    // 添加标题
    svg.append('text')
        .attr('x', width / 2)
        .attr('y', -10)
        .attr('text-anchor', 'middle')
        .text('涨跌分布');
}

// 渲染涨跌停数量曲线图
function renderZdtcountChart(data) {
    const container = d3.select('#zdtcount-chart');
    container.html('');
    
    const margin = {top: 20, right: 30, bottom: 40, left: 40};
    const width = container.node().clientWidth - margin.left - margin.right;
    const height = 300 - margin.top - margin.bottom;
    
    const svg = container.append('svg')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('g')
        .attr('transform', `translate(${margin.left},${margin.top})`);
    
    // 设置比例尺
    const x = d3.scaleBand()
        .domain(data.map(d => d.time))
        .range([0, width])
        .padding(0.1);
        
    const y = d3.scaleLinear()
        .domain([0, d3.max(data, d => Math.max(d.upLimit, d.downLimit))])
        .nice()
        .range([height, 0]);
    
    // 添加涨停曲线
    const upLine = d3.line()
        .x(d => x(d.time) + x.bandwidth() / 2)
        .y(d => y(d.upLimit));
        
    svg.append('path')
        .datum(data)
        .attr('fill', 'none')
        .attr('stroke', '#e74c3c')
        .attr('stroke-width', 2)
        .attr('d', upLine);
    
    // 添加跌停曲线
    const downLine = d3.line()
        .x(d => x(d.time) + x.bandwidth() / 2)
        .y(d => y(d.downLimit));
        
    svg.append('path')
        .datum(data)
        .attr('fill', 'none')
        .attr('stroke', '#2ecc71')
        .attr('stroke-width', 2)
        .attr('d', downLine);
    
    // 添加X轴
    svg.append('g')
        .attr('transform', `translate(0,${height})`)
        .call(d3.axisBottom(x))
        .selectAll('text')
        .attr('transform', 'rotate(-45)')
        .style('text-anchor', 'end');
    
    // 添加Y轴
    svg.append('g')
        .call(d3.axisLeft(y));
    
    // 添加标题
    svg.append('text')
        .attr('x', width / 2)
        .attr('y', -10)
        .attr('text-anchor', 'middle')
        .text('涨跌停数量');
    
    // 添加图例
    const legend = svg.append('g')
        .attr('transform', `translate(${width - 100}, 0)`);
        
    legend.append('rect')
        .attr('width', 12)
        .attr('height', 12)
        .attr('fill', '#e74c3c');
        
    legend.append('text')
        .attr('x', 20)
        .attr('y', 10)
        .text('涨停数量')
        .style('font-size', '12px');
        
    legend.append('rect')
        .attr('y', 20)
        .attr('width', 12)
        .attr('height', 12)
        .attr('fill', '#2ecc71');
        
    legend.append('text')
        .attr('x', 20)
        .attr('y', 30)
        .text('跌停数量')
        .style('font-size', '12px');
}

// 渲染封板失败数量曲线图
function renderFbfailedChart(data) {
    const container = d3.select('#fbfailed-chart');
    container.html('');
    
    const margin = {top: 20, right: 40, bottom: 40, left: 40};
    const width = container.node().clientWidth - margin.left - margin.right;
    const height = 300 - margin.top - margin.bottom;
    
    const svg = container.append('svg')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('g')
        .attr('transform', `translate(${margin.left},${margin.top})`);
    
    // 设置比例尺
    const x = d3.scaleBand()
        .domain(data.map(d => d.time))
        .range([0, width])
        .padding(0.1);
        
    const y1 = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.count)])
        .nice()
        .range([height, 0]);
        
    const y2 = d3.scaleLinear()
        .domain([0, 100]) // 百分比范围0-100
        .range([height, 0]);
    
    // 添加数量曲线
    const countLine = d3.line()
        .x(d => x(d.time) + x.bandwidth() / 2)
        .y(d => y1(d.count));
        
    svg.append('path')
        .datum(data)
        .attr('fill', 'none')
        .attr('stroke', '#3498db')
        .attr('stroke-width', 2)
        .attr('d', countLine);
    
    // 添加失败率曲线
    const ratioLine = d3.line()
        .x(d => x(d.time) + x.bandwidth() / 2)
        .y(d => y2(d.failedRatio));
        
    svg.append('path')
        .datum(data)
        .attr('fill', 'none')
        .attr('stroke', '#9b59b6')
        .attr('stroke-width', 2)
        .attr('stroke-dasharray', '5,5')
        .attr('d', ratioLine);
    
    // 添加X轴
    svg.append('g')
        .attr('transform', `translate(0,${height})`)
        .call(d3.axisBottom(x))
        .selectAll('text')
        .attr('transform', 'rotate(-45)')
        .style('text-anchor', 'end');
    
    // 添加左侧Y轴(数量)
    svg.append('g')
        .call(d3.axisLeft(y1))
        .append('text')
        .attr('y', -10)
        .attr('x', -30)
        .attr('text-anchor', 'end')
        .text('数量');
    
    // 添加右侧Y轴(百分比)
    svg.append('g')
        .attr('transform', `translate(${width},0)`)
        .call(d3.axisRight(y2))
        .append('text')
        .attr('y', -10)
        .attr('x', 30)
        .attr('text-anchor', 'start')
        .text('失败率(%)');
    
    // 添加标题
    svg.append('text')
        .attr('x', width / 2)
        .attr('y', -10)
        .attr('text-anchor', 'middle')
        .text('封板失败情况');
    
    // 添加图例
    const legend = svg.append('g')
        .attr('transform', `translate(${width - 150}, 0)`);
        
    legend.append('rect')
        .attr('width', 12)
        .attr('height', 12)
        .attr('fill', '#3498db');
        
    legend.append('text')
        .attr('x', 20)
        .attr('y', 10)
        .text('封板失败数量')
        .style('font-size', '12px');
        
    legend.append('rect')
        .attr('y', 20)
        .attr('width', 12)
        .attr('height', 12)
        .attr('fill', '#9b59b6');
        
    legend.append('text')
        .attr('x', 20)
        .attr('y', 30)
        .text('封板失败率')
        .style('font-size', '12px');
}

// 渲染涨停池表格
function renderZtpoolTable(data) {
    const container = d3.select('#ztpool-table');
    container.html('');
    
    // 创建表格元素
    const table = container.append('table')
        .attr('class', 'zt-table');
    
    // 添加表头
    const thead = table.append('thead');
    const headers = [
        {name: '代码', field: 'code'},
        {name: '名称', field: 'name'},
        {name: '价格', field: 'price'},
        {name: '涨幅%', field: 'changePct'},
        {name: '成交额(亿)', field: 'amount'},
        {name: '流通市值(亿)', field: 'ltsz'},
        {name: '封板时间', field: 'fbt'},
        {name: '最后封板', field: 'lbt'},
        {name: '封单金额(亿)', field: 'fund'},
        {name: '连板天数', field: 'zttjDays'}
    ];
    
    thead.append('tr')
        .selectAll('th')
        .data(headers)
        .enter()
        .append('th')
        .text(d => d.name)
        .on('click', function(_, d) {
            const isAscending = !d3.select(this).classed('asc');
            d3.selectAll('th').classed('asc', false).classed('desc', false);
            d3.select(this).classed(isAscending ? 'asc' : 'desc', true);
            sortTable(d.field, data, isAscending);
            renderZtpoolTable(data);
        });
    
    // 添加表格内容
    const tbody = table.append('tbody');
    
    const rows = tbody.selectAll('tr')
        .data(data)
        .enter()
        .append('tr');
    
    // 格式化金额(亿)
    const formatAmount = val => (val / 100000000).toFixed(2);
    
    // 添加单元格
    rows.selectAll('td')
        .data(row => [
            row.code,
            row.name,
            row.price.toFixed(2),
            row.changePct.toFixed(2),
            formatAmount(row.amount),
            (row.ltsz / 100000000).toFixed(2),
            row.fbt,
            row.lbt,
            (row.fund / 100000000).toFixed(2),
            row.zttjDays
        ])
        .enter()
        .append('td')
        .text(d => d);
    
    // 添加表格样式
    container.append('style')
        .text(`
            .zt-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }
            .zt-table th, .zt-table td {
                padding: 8px 12px;
                border: 1px solid #ddd;
                text-align: center;
            }
            .zt-table th {
                background-color: #f5f5f5;
                cursor: pointer;
                position: relative;
            }
            .zt-table th:hover {
                background-color: #eaeaea;
            }
            .zt-table th.asc::after {
                content: '↑';
                margin-left: 5px;
            }
            .zt-table th.desc::after {
                content: '↓';
                margin-left: 5px;
            }
            .zt-table tr:nth-child(even) {
                background-color: #f9f9f9;
            }
            .zt-table tr:hover {
                background-color: #f0f0f0;
            }
        `);
}

// 表格排序函数
function sortTable(columnName, data, isAscending) {
    data.sort((a, b) => {
        const valA = a[columnName];
        const valB = b[columnName];
        
        if (typeof valA === 'string') {
            return isAscending 
                ? valA.localeCompare(valB)
                : valB.localeCompare(valA);
        } else {
            return isAscending 
                ? valA - valB
                : valB - valA;
        }
    });
}

// 渲染昨日涨停表格
function renderYesZtpoolTable(data) {
    const container = d3.select('#yes-ztpool-table');
    container.html('');
    
    // 创建表格元素
    const table = container.append('table')
        .attr('class', 'zt-table');
    
    // 添加表头
    const thead = table.append('thead');
    const headers = [
        {name: '代码', field: 'code'},
        {name: '名称', field: 'name'},
        {name: '价格', field: 'price'},
        {name: '涨幅%', field: 'changePct'},
        {name: '成交额(亿)', field: 'amount'},
        {name: '流通市值(亿)', field: 'ltsz'},
        {name: '昨日封板时间', field: 'yfbt'},
        {name: '连板天数', field: 'zttjDays'},
        {name: '概念板块', field: 'hybk'}
    ];
    
    thead.append('tr')
        .selectAll('th')
        .data(headers)
        .enter()
        .append('th')
        .text(d => d.name)
        .on('click', function(_, d) {
            const isAscending = !d3.select(this).classed('asc');
            d3.selectAll('th').classed('asc', false).classed('desc', false);
            d3.select(this).classed(isAscending ? 'asc' : 'desc', true);
            sortTable(d.field, data, isAscending);
            renderYesZtpoolTable(data);
        });
    
    // 添加表格内容
    const tbody = table.append('tbody');
    
    const rows = tbody.selectAll('tr')
        .data(data)
        .enter()
        .append('tr');
    
    // 格式化金额(亿)
    const formatAmount = val => (val / 100000000).toFixed(2);
    
    // 添加单元格
    rows.selectAll('td')
        .data(row => [
            row.code,
            row.name,
            row.price.toFixed(2),
            row.changePct.toFixed(2),
            formatAmount(row.amount),
            (row.ltsz / 100000000).toFixed(2),
            row.yfbt,
            row.zttjDays,
            row.hybk
        ])
        .enter()
        .append('td')
        .text(d => d);
    
    // 复用涨停池表格样式
    container.append('style')
        .text(`
            .zt-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }
            .zt-table th, .zt-table td {
                padding: 8px 12px;
                border: 1px solid #ddd;
                text-align: center;
            }
            .zt-table th {
                background-color: #f5f5f5;
                cursor: pointer;
                position: relative;
            }
            .zt-table th:hover {
                background-color: #eaeaea;
            }
            .zt-table th.asc::after {
                content: '↑';
                margin-left: 5px;
            }
            .zt-table th.desc::after {
                content: '↓';
                margin-left: 5px;
            }
            .zt-table tr:nth-child(even) {
                background-color: #f9f9f9;
            }
            .zt-table tr:hover {
                background-color: #f0f0f0;
            }
        `);
}

// 渲染概念板块表格
function renderGnTop10Table(data) {
    const container = d3.select('#gn-top10-table');
    container.html('');
    
    // 创建表格元素
    const table = container.append('table')
        .attr('class', 'gn-table');
    
    // 添加表头
    const thead = table.append('thead');
    const headers = [
        {name: '板块名称', field: 'boardName'},
        {name: '涨跌幅%', field: 'changePercent'},
        {name: '换手率%', field: 'turnoverRate'},
        {name: '总市值(亿)', field: 'totalMarketValue'},
        {name: '上涨家数', field: 'risingCount'},
        {name: '下跌家数', field: 'fallingCount'},
        {name: '龙头股', field: 'topStockName'},
        {name: '龙头涨幅%', field: 'topStockRise'},
        {name: '最弱股', field: 'lowestStockName'},
        {name: '最弱跌幅%', field: 'lowestStockPercent'}
    ];
    
    thead.append('tr')
        .selectAll('th')
        .data(headers)
        .enter()
        .append('th')
        .text(d => d.name)
        .on('click', function(_, d) {
            const isAscending = !d3.select(this).classed('asc');
            d3.selectAll('th').classed('asc', false).classed('desc', false);
            d3.select(this).classed(isAscending ? 'asc' : 'desc', true);
            sortTable(d.field, data, isAscending);
            renderGnTop10Table(data);
        });
    
    // 添加表格内容
    const tbody = table.append('tbody');
    
    const rows = tbody.selectAll('tr')
        .data(data)
        .enter()
        .append('tr');
    
    // 格式化金额(亿)
    const formatMarketValue = val => (val / 100000000).toFixed(2);
    
    // 添加单元格
    rows.selectAll('td')
        .data(row => [
            row.boardName,
            row.changePercent.toFixed(2),
            row.turnoverRate.toFixed(2),
            formatMarketValue(row.totalMarketValue),
            row.risingCount,
            row.fallingCount,
            `${row.topStockName}(${row.topStockCode})`,
            row.topStockRise.toFixed(2),
            `${row.lowestStockName}(${row.lowestStockCode})`,
            row.lowestStockPercent.toFixed(2)
        ])
        .enter()
        .append('td')
        .text(d => d);
    
    // 添加表格样式
    container.append('style')
        .text(`
            .gn-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }
            .gn-table th, .gn-table td {
                padding: 8px 12px;
                border: 1px solid #ddd;
                text-align: center;
            }
            .gn-table th {
                background-color: #f5f5f5;
                cursor: pointer;
                position: relative;
            }
            .gn-table th:hover {
                background-color: #eaeaea;
            }
            .gn-table th.asc::after {
                content: '↑';
                margin-left: 5px;
            }
            .gn-table th.desc::after {
                content: '↓';
                margin-left: 5px;
            }
            .gn-table tr:nth-child(even) {
                background-color: #f9f9f9;
            }
            .gn-table tr:hover {
                background-color: #f0f0f0;
            }
            .gn-table td:nth-child(2) {
                color: #e74c3c;
                font-weight: bold;
            }
            .gn-table td:nth-child(8) {
                color: #e74c3c;
            }
            .gn-table td:nth-child(10) {
                color: #2ecc71;
            }
        `);
}

// 表格排序函数
function sortTable(columnName, data, isAscending) {
    // 实现表格排序逻辑
    // ...
}
